import 'dart:async';
import 'dart:isolate';

import 'package:dmz/base/controller/base_controller.dart';
import 'package:dmz/business/home/controller/home_main_controller.dart';
import 'package:dmz/business/home/model/moto_model.dart';
import 'package:dmz/business/home/model/moto_version.dart';
import 'package:dmz/business/home/widgets/ErrorDialog.dart';
import 'package:dmz/business/home/widgets/ota_upgrad.dart';
import 'package:dmz/business/home/widgets/bind_success_widget.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/tools/blue/blue_manger.dart';
import 'package:dmz/user/user_defurl.dart';
import 'package:dmz/utils/Utils.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/material.dart';

import 'package:flutter/services.dart';
import 'package:get/get.dart';

import '../../../request/api_response_entity.dart';
import '../../../request/apis.dart';
import '../../mine/model/card_detail.dart';
import '../model/moto_ota_result.dart';
import '../../../routers/routers.dart';

class SetMotoInforController extends BaseController {
  MotoModel? data;
  MotoVersion? motoVersion;
  UserCardDetail userCardDetail = UserCardDetail();
  bool showBottom = false;
  bool defaultBottom = false;
  bool forceBottom = false;
  List<String> contents = ['', '', '', '', '', ''];
  bool showUpdate = false;
  int? index;
  int? otaId;
  String? versionName;
  bool updateThread = false;
  String? cardVersion;

  List<TextEditingController> transferInputCT = [TextEditingController()];
  // List<FocusNode> transferFocusNodes = [FocusNode()];

  @override
  void loadNet() {}

  @override
  void onHidden() {}

  @override
  void onInit() {
    debugPrint('获取车辆信息000 ---  ');
    var homeController = Get.find<HomePageController>();
    index = homeController.pageIndex;
    data = homeController.motoList[homeController.pageIndex];
    motoVersion = homeController.motoVersion;
    showBottom = homeController.showBottom;
    defaultBottom = homeController.defaultBottom;
    forceBottom = homeController.forceBottom;
    contents[0] = data?.device_type_name ?? '';
    contents[1] = data?.imei ?? '';
    contents[2] = data?.sn_code ?? '';
    contents[3] = data?.frame_code ?? '';
    contents[4] = EMIBUserManger().user?.phone ?? '';
    otaId = motoVersion!.id;
    debugPrint('获取车辆信息 --- ${data?.id}');
    getUserBikeInfo(data!.id);
    initVersion();
    update(['setInfoMoto']);
    // contents[5] = data?.device_type_name ?? '';
    super.onInit();
  }

  didCopy(int tag) async {
    await Clipboard.setData(ClipboardData(text: contents[tag]));
    EMILoding.hitLoding('复制成功'.tr, isScuess: true);
  }

  initVersion() {
    if (showBottom) {
      //弹窗过来的
      showUpdate = false;
      otaUpdate();
    } else {
      //页面跳转过来的
      getVersion(data!.sn_code);
    }
  }

  void getVersion(String? sn_code) {
    RequestClient().post<MotoVersion>(APIS.checkVersion,
        data: {'sn_code': sn_code}).then((value) {
      if (value != null) {
        motoVersion = value;
      } else {
        motoVersion = MotoVersion();
      }
      if (Utils.isNotEmptyString(motoVersion!.ebike_name)) {
        debugPrint('initVersion ------------------ ${motoVersion!.ebike_name}');
        showUpdate = true;
        if (motoVersion!.upgrade_type == 1) {
          //自主升级
          defaultBottom = true;
        } else if (motoVersion!.upgrade_type == 2) {
          //强制升级
          forceBottom = true;
        }
      } else {
        debugPrint('initVersion ======================');
        showUpdate = false;
      }
      update(['setInfoMoto']);
      debugPrint('检测新版本');
    });
  }

  void getUserBikeInfo(deviceId) {
    RequestClient().post<UserCardDetail>(APIS.motoBikeInfo,
        data: {'ebike_id': deviceId}).then((value) {
      if (value != null) {
        userCardDetail = value;
        contents[1] = value.imei ?? '';
        cardVersion = userCardDetail.firmware_version ?? '';
        update(['setInfoMoto']);
      }
    });
  }

  otaUpdate() {
    showUpdate = false;
    RequestClient().post<MotoOtaResult>(APIS.upgrade, data: {
      'id': motoVersion!.id,
      'sn_code': data!.sn_code,
      'status': 0,
      'plan_id': motoVersion!.plan_id,
      'strategy_id': motoVersion!.strategy_id
    }, onResponse: (value) {
      ApiResponse api = value;
      api.code;
      if (api.code == 0 || 'ok' == api.msg) {
        if (forceBottom) {
          EMILoding.showBottomWindow(
            OtaUpgradingDialog(),
          );
        }
        if (defaultBottom) {
          EMILoding.hitLoding('正在升级中'.tr);
        }
        updateThread = true;
        iSolt();
        debugPrint('检测新版本');
      }
    });
  }

  otaResult() {
    RequestClient()
        .post<MotoOtaResult>(APIS.result, data: {'id': otaId}).then((value) {
      if (value != null) {
        MotoOtaResult result = value;
        switch (result.status) {
          case 2: //升级中
            break;
          case 3:
            if (forceBottom) {
              Get.back();
            }
            updateThread = false;
            //升级成功
            forceBottom = false;
            EMILoding.hitLoding('升级成功'.tr);
            update(['setInfoMoto']);
            getUserBikeInfo(data!.id);
            break;
          case 4:
            if (forceBottom) {
              Get.back();
            }
            updateThread = false;
            forceBottom = false;
            EMILoding.showBottomWindow(
              ErrorDialog(),
            );
            update(['setInfoMoto']);
            break;
          default:
            forceBottom = false;
            updateThread = false;
            update(['setInfoMoto']);
            break;
        }
      }
      debugPrint('检测新版本');
    });
  }

  Isolate? timerIsolate;

  void iSolt() async {
    Timer.periodic(const Duration(seconds: 5), (Timer timer) {
      if (updateThread) {
        otaResult();
      }
    });
  }

  @override
  onClose() {
    super.onClose();
    updateThread = false;
    update(['setInfoMoto']);
  }

  btnClick(index) {
    index == 0 ? unbind() : Get.toNamed(RouteGet.transferMoto);
  }

  unbind() {
    if (data?.is_manager != '1') {
      return EMILoding.hitLoding('该功能仅对车主开放'.tr);
    }
    EMILoding.showBottomHitWindow(
        '确定解除绑定吗？'.tr, '车辆信息、行程，订单，轨迹，行车记录信息支持保存一年，过期后数据会自动删除。'.tr, (agree) {
      Get.back();
      if (agree) {
        RequestClient().post<Map>(APIS.unbind, data: {
          'sn_code': data?.sn_code ?? '',
          'id': EMIBUserManger().user?.Id ?? 0
        }).then((value) {
          EMIBlueMangered().disContenWidhSNCode(data?.sn_code ?? '');
          Get.find<HomePageController>().getMotolist();
          EMILoding.hitLoding('解除绑定成功'.tr, isScuess: true);
          Get.until((route) => route.settings.name == RouteGet.main);
        });
      }
    });
  }

  transferAddInput() {
    if (transferInputCT.length == 5) return;
    transferInputCT.add(TextEditingController());
    update(['transfer']);
  }

  inputChange(int tag) {
    transferInputCT.removeAt(tag);
    update(['transfer']);
  }

  didTransfer() {
    var datas = transferInputCT.where((element) => element.text.length < 5);
    if (datas.isNotEmpty) {
      return EMILoding.hitLoding('请输入正确手机号'.tr);
    }

    RequestClient().post<Map>(APIS.getSetting, data: {
      'ebike_id': data?.id ?? 0,
      'target_phones': transferInputCT
          .map((controller) => int.parse(controller.text))
          .toList()
    }).then((value) {
      EMILoding.showBottomWindow(BindSuccess(
          bakc: (type) {
            EMIBlueMangered().disContenWidhSNCode(data?.sn_code ?? '');
            Get.find<HomePageController>().getMotolist();
            Get.until((route) => route.settings.name == RouteGet.main);
          },
          title: '授权成功！'.tr));
    });
  }
}

class SetMotoInforBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => SetMotoInforController());
  }
}
